package com.ita.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;


public class DBUtil {

	private static String DRIVER_NAME="oracle.jdbc.OracleDriver";
	private static String URL="jdbc:oracle:thin:@zha-ita105-w7:1521:orcl";
	private static String USER_NAME="bryce";
	private static String PASSWORD="123";

	private static BasicDataSource dbcpDs;
	private static DataSource jndiDs;

	static {
//		Properties prop = new Properties();
//		InputStream in = null;
//		try {
//			in = new BufferedInputStream(new FileInputStream(
//					"prop/DB.properties"));
//			prop.load(in);
//			DRIVER_NAME = prop.getProperty("DRIVER_NAME");
//			URL = prop.getProperty("URL");
//			USER_NAME = prop.getProperty("USER_NAME");
//			PASSWORD = prop.getProperty("PASSWORD");
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (in != null) {
//				try {
//					in.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
		
		try {
			Context cxt= new InitialContext();
			jndiDs = (DataSource)cxt.lookup("java:/comp/env/jdbc/myoracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
		dbcpDs = new BasicDataSource();
		dbcpDs.setDriverClassName(DRIVER_NAME);
		dbcpDs.setUrl(URL);
		dbcpDs.setUsername(USER_NAME);
		dbcpDs.setPassword(PASSWORD);
	}

	public static Connection createConnection() {

		Connection conn = null;
		try {
			Class.forName(DRIVER_NAME);
			conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static Connection createConnectionWithDataSource() {

		Connection conn = null;
		try {
			return dbcpDs.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static Connection createByJNDI() {

		Connection conn = null;
		try {
			return jndiDs.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static void close(Connection conn, PreparedStatement pst,
			ResultSet rSet) {

		try {
			if (conn != null) {
				conn.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (rSet != null) {
				rSet.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
